package com.project.erp.interceptor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.project.erp.common.Constants;
import com.project.erp.model.system.Privilege;
import com.project.erp.model.system.User;

public class LoginInterceptor extends MethodFilterInterceptor{
	
	/**
	 * 系统登陆后可以访问的URL不需进行权限的认证
	 */
	protected Set<String> excludeUrls = Collections.emptySet();
	
	public Set<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(String excludeUrls) {
		this.excludeUrls = TextParseUtil.commaDelimitedStringToSet(excludeUrls);
	}

	private static final long serialVersionUID = -7191267218207106751L;

	/**
	 * 如果是传统访问，直接返回视图给前端页面进行跳转
	 * 如果是ajax访问，系统将返回对应的错误状态码交由前端ajax的全局设置函数进行跳转
	 * 错误码403表示操作未授权，500表示后台java服务端出现内部错误，408表示请求超时，session清空，自动跳转到登陆页面。
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		
		boolean flag = false;	  //判断操作权限用的标示,有权限为true
		boolean ajaxflag = false; //是否ajax请求，是为true
		ActionContext ctx = invocation.getInvocationContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String nameSpace = invocation.getProxy().getNamespace();
		if(StringUtils.isNotBlank(nameSpace)){
			if(!"/".equals(nameSpace.trim())){
				nameSpace += "/";
			}
		}
		String actionName = invocation.getProxy().getActionName();
		String requestAction = nameSpace + actionName + ".action";
		ajaxflag = isAjaxRequest(request);
		User currentUser = (User) ctx.getSession().get(Constants.ERP_CURRENT_USER);
		//用户没有登录系统
		if(null == currentUser)
		{
			//如果是ajax请求
			if(ajaxflag){
				response.setHeader("sessionstatus", "sessionOut");
				//response.getWriter().print("sessionOut");
				return invocation.invoke();
			}else{
				//跳转到用户登录页面去
				return "toLogin";
			}
		}
		//登陆用户共有URL资源,包含系统请求后台资源信息，放过不需要拦截,不需要判断资源文件是否包含
		if(excludeUrls.contains(requestAction)){
			return invocation.invoke();
		}
		//用户拥有的权限
		List<Privilege> rightPrivilege = (List<Privilege>)ctx.getSession().get(Constants.ERP_CURRENT_USER_RIGHTCODES);
		List<String> rightURL = new ArrayList<String>();
		for (Privilege privilege : rightPrivilege) {
			if(StringUtils.isNotBlank(privilege.getUrl())){
				rightURL.add(privilege.getUrl());
				if(StringUtils.isNotBlank(privilege.getExternal())){
					String[] urlArray = privilege.getExternal().split(Constants.PRIVILEGE_EXTERNAL_SPLIT);
					for (String url : urlArray) {
						rightURL.add(url);
					}
				}
			}
		}
		//有权限
		if(rightURL.contains(requestAction)){
			flag = true;
		}
		//拦截没有权限的操作,根据用户配置资源url权限进行处理
		if(!flag)
		{
			//System.out.println("拦截器验证：用户无功能的操作权限，已被系统拦截。。");
			//如果是ajax请求
			if(ajaxflag){
				response.sendError(403);
				return "noauth";
			}else{
				//跳转到用户登录页面去
				return "noauth";
			}
		}
		
		return invocation.invoke();
	}

	/**
	 * 判断是否是ajax访问
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}
}
